<template>
  <div class="character-cards-page">
    <!-- <el-page-header content="角色卡管理" :show-back="false" /> -->

    <!-- 工具栏 -->
    <el-row :gutter="20" class="toolbar">
      <el-col :span="14">
        <el-button type="primary" @click="showCreateDialog">新增角色卡</el-button>
      </el-col>
      <el-col :span="8" class="text-right">
        <el-input v-model="searchKeyword" placeholder="搜索角色名" style="width: 300px;" clearable />
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="fetchCharacterCards">搜索</el-button>
      </el-col>
    </el-row>

    <!-- 角色卡列表 -->
    <el-table :data="characterCards" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名" width="150" />
      <el-table-column prop="faction" label="阵营" width="120" />
      <el-table-column prop="title" label="称号" width="150" />
      <el-table-column prop="temperature" label="Temperature" width="150" />
      <el-table-column prop="top_p" label="Top P" width="100" />
      <el-table-column prop="enabled" label="状态" width="100" show-overflow-tooltip>
        <template #default="{ row }">
          <el-tag size="small" type="success" v-if="row.enabled">启用</el-tag>
          <el-tag size="small" type="warning" v-else>禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="text" size="small" @click="startCharacterCard(row.id)">启动</el-button>
          <el-button type="text" size="small" style="color: #f56c6c;" @click="bandCharacterCard(row.id)">禁用</el-button>
          <el-button type="text" size="small" @click="showEditDialog(row)">编辑</el-button>
          <el-popconfirm title="确定要删除该角色卡吗？" @confirm="deleteCharacterCard(row.id)">
            <template #reference>
              <el-button type="text" size="small" style="color: #f56c6c;">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <!-- <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="characterCards.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    /> -->

    <!-- 新增/编辑 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色卡' : '新增角色卡'"
      width="70%"
      :before-close="closeDialog"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名" />
        </el-form-item>
        <el-form-item label="阵营" prop="faction">
          <el-input v-model="form.faction" placeholder="请输入阵营" />
        </el-form-item>
        <el-form-item label="称号" prop="title">
          <el-input v-model="form.title" placeholder="请输入称号" />
        </el-form-item>
        <el-form-item label="性格">
          <el-input v-model="form.personality" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="说话风格">
          <el-input v-model="form.speech_style" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="背景故事">
          <el-input v-model="form.background" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="互动规则">
          <el-input v-model="form.interaction_rules" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="口头禅">
          <el-input v-model="form.catchphrases" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="行为模式">
          <el-input v-model="form.behavior_patterns" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="禁忌内容">
          <el-input v-model="form.prohibited" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="对话示例">
          <el-input v-model="form.dialogue_examples" type="textarea" :rows="4" placeholder="" />
        </el-form-item>
        <el-form-item label="Temperature">
          <el-input-number v-model="form.temperature" placeholder="数值" :step="0.1" :precision="2"/>
        </el-form-item>
        <el-form-item label="Top P">
          <el-input-number v-model="form.top_p" placeholder="数值" :step="0.1" :precision="2"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import * as characterCardApi from '@/api/characterCard_api'

// 查询参数
const page = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')

// 角色卡列表
const characterCards = ref([])
const filteredCharacterCards = ref([])

// 表单和弹窗
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

// 1. 定义表单默认模板
const formDefault = {
  id: '',
  name: '',
  faction: '',
  title: '',
  personality: '',
  speech_style: '',
  background: '',
  interaction_rules: '',
  catchphrases: '',
  behavior_patterns: '',
  prohibited: '',
  dialogue_examples: '',
  temperature: 0.7,
  top_p: 0.9
}

// 2. 初始化表单（替换原有的 form 定义）
const form = reactive({ ...formDefault })



// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  faction: [{ required: true, message: '请输入阵营', trigger: 'blur' }],
  title: [{ required: true, message: '请输入称号', trigger: 'blur' }]
})

// 获取所有角色卡
const fetchCharacterCards = async () => {
  try {
    const keyword = searchKeyword.value.trim().toLowerCase()
    //如果搜索词为空，获取所有角色卡
    if (!keyword) {
      const res = await characterCardApi.getCharacterCards()
      if (res.data.code === 0) {
        characterCards.value = res.data.data
        return
      } else {
        ElMessage.error('获取角色卡失败: ' + res.data.message)
        return
      }
    }else{
      const res = await characterCardApi.getCharacterCardsByName(keyword)
      if (res.data.code === 0) {
        characterCards.value = res.data.data
        //filterCharacterCards()
      } else {
        ElMessage.error('获取角色卡失败: ' + res.data.message)
      }
    }
  } catch (error) {
    ElMessage.error('获取角色卡失败')
    console.error(error)
  }
}

// 过滤角色卡（搜索）
// const filterCharacterCards = () => {
//   const keyword = searchKeyword.value.trim().toLowerCase()
//   if (keyword) {
//     filteredCharacterCards.value = characterCards.value.filter(card =>
//       card.name.toLowerCase().includes(keyword) ||
//       card.faction.toLowerCase().includes(keyword) ||
//       card.title.toLowerCase().includes(keyword)
//     )
//   } else {
//     // 搜索词为空时，显示全部角色卡
//     filteredCharacterCards.value = [...characterCards.value]
//   }
// }


// 分页处理
// const handleSizeChange = (size) => {
//   pageSize.value = size
//   page.value = 1
//   filterCharacterCards()
// }
// const handleCurrentChange = (p) => {
//   page.value = p
//   filterCharacterCards()
// }

// 新增角色卡
const showCreateDialog = () => {
  isEdit.value = false
  // 重置表单验证
  formRef.value && formRef.value.resetFields()
  // 重置表单数据为默认模板
  Object.assign(form, { ...formDefault })  
  dialogVisible.value = true
}

// 编辑角色卡
const showEditDialog = (row) => {
  isEdit.value = true
  form.id = row.id
  form.name = row.name
  form.faction = row.faction
  form.title = row.title
  form.personality = typeof row.personality === 'string' ? row.personality : JSON.stringify(row.personality, null, 2)
  form.speech_style = typeof row.speech_style === 'string' ? row.speech_style : JSON.stringify(row.speech_style, null, 2)
  form.background = typeof row.background === 'string' ? row.background : JSON.stringify(row.background, null, 2)
  form.interaction_rules = typeof row.interaction_rules === 'string' ? row.interaction_rules : JSON.stringify(row.interaction_rules, null, 2)
  form.catchphrases = typeof row.catchphrases === 'string' ? row.catchphrases : JSON.stringify(row.catchphrases, null, 2)
  form.behavior_patterns = typeof row.behavior_patterns === 'string' ? row.behavior_patterns : JSON.stringify(row.behavior_patterns, null, 2)
  form.prohibited = typeof row.prohibited === 'string' ? row.prohibited : JSON.stringify(row.prohibited, null, 2)
  form.dialogue_examples = typeof row.dialogue_examples === 'string' ? row.dialogue_examples : JSON.stringify(row.dialogue_examples, null, 2)
  form.temperature = row.temperature
  form.top_p = row.top_p
  dialogVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  // 等待 300ms 让弹窗动画完成
  // 确保 DOM 完全隐藏并释放后再重置
  setTimeout(() => {
    formRef.value && formRef.value.resetFields()
  }, 300)
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 处理 JSON 字段
    const payload = { ...form }
    // try {
    //   payload.personality = JSON.parse(form.personality)
    //   payload.speech_style = JSON.parse(form.speech_style)
    //   payload.background = JSON.parse(form.background)
    //   payload.interaction_rules = JSON.parse(form.interaction_rules)
    //   payload.catchphrases = JSON.parse(form.catchphrases)
    //   payload.behavior_patterns = JSON.parse(form.behavior_patterns)
    //   payload.prohibited = JSON.parse(form.prohibited)
    //   payload.dialogue_examples = JSON.parse(form.dialogue_examples)


    // } catch (e) {
    //   ElMessage.error('JSON 格式错误')
    //   return
    // }

    if (isEdit.value) {
      const response = await characterCardApi.updateCharacterCard(form.id, payload)
      if (response.data.code === 0) {
        ElMessage.success('角色卡更新成功')
      } else {
          ElMessage.error('更新失败: ' + response.data.message)
      }
    } else {
      const response = await characterCardApi.createCharacterCard(payload)
      if (response.data.code === 0) {
        ElMessage.success('角色卡创建成功')
      } else {
          ElMessage.error('创建失败: ' + response.data.message)
      }
    }

    dialogVisible.value = false
    fetchCharacterCards()
  } catch (error) {
    console.error(error)
    ElMessage.error('操作失败')
  }
}

// 删除角色卡
const deleteCharacterCard = async (id) => {
  try {
    const response = await characterCardApi.deleteCharacterCard(id)
    if (response.data.code === 0) {
        ElMessage.success('角色卡删除成功')
        fetchCharacterCards()
    } else {
        ElMessage.error('删除失败: ' + response.data.message)
    }
  } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
  }
}

//启动角色卡
const startCharacterCard = async (id) => {
  try {
    const data = {id:id}
    const response = await characterCardApi.startCharacterCard(id)
    if (response.data.code === 0) {
        ElMessage.success('角色卡启动成功')
        fetchCharacterCards()
    } else {
        ElMessage.error('启动失败: ' + response.data.message)
    }
  } catch (error) {
      ElMessage.error('启动失败')
      console.error(error)
  }

}


//禁用角色卡
const bandCharacterCard = async (id) => {
  try {
    const data = {id:id}
    const response = await characterCardApi.bandCharacterCard(id)
    if (response.data.code === 0) {
        ElMessage.success('角色卡禁用成功')
        fetchCharacterCards()
    } else {
        ElMessage.error('禁用失败: ' + response.data.message)
    }
  } catch (error) {
      ElMessage.error('禁用失败')
      console.error(error)
  }  

}


// 初始化
onMounted(() => {
  fetchCharacterCards()
  searchKeyword.value = ''
})
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}
</style>